package com.my.meitianbackup.controller;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.my.meitianbackup.common.Constants;
import com.my.meitianbackup.model.Meitian;

public class IndexController extends Controller {
	public static List<Meitian> meitianList = new ArrayList<Meitian>();
	
	public void index() {

		render("index.jsp");
	}
	
	public void catePage() {
		String dateStr = getPara("date");
		String cate = getPara("cate");
		System.out.println(dateStr + "-" +cate + "-" +getCateNum(cate));
		meitianList = Meitian.dao.find("select * from meitian where `couponEnd` >= ? and `publishDate` is null and hasInfo =1 and hasImgs = 1 and isDeleted != 1 and cate = ? order by sales desc limit ?", dateStr, cate, getCateNum(cate));
		updateSelect(meitianList);
		setAttr("data",meitianList);
		render("catePage.jsp");
	}
	
	public void updateSelect(List<Meitian> meitianList) {
		for(Meitian meitian : meitianList) {
			meitian.setIsSelected(1);
		}
		Db.batchUpdate(meitianList, meitianList.size());
	}
	
	public void changeItem() {
		String id = getPara("id");
		String cate = getPara("cate");
		String dateStr = getPara("date");
		List<Meitian> meitianList = Meitian.dao.find("select * from meitian where `couponEnd` >= ? and hasInfo =1 and hasImgs = 1 and isSelected = 0 and isDeleted = 0 and cate = ? order by sales desc limit 1",dateStr,cate);
		updateSelect(meitianList);
		setAttr("data",meitianList);
		Db.update("update meitian set `publishDate` = null , isSelected = 0, isDeleted = 1 where id = ?", id);
		render("catePage.jsp");
	}
	
	public void countNum() {
		String dateStr = getPara("date");
		Long count = Db.queryLong("select count(*) from meitian where publishDate = ? and isSelected = 1",dateStr);
		JSONObject jb = new JSONObject();
		jb.put("count", count);
		renderJson(jb.toString());
	}
	
	public void save() {
		String dateStr = getPara("date");
		int sum = 0;
		for(int i=0 ;i<Constants.catesEn.length; i++){
			int n = Db.update("update meitian set `publishDate` = ? where cateEn = ? and isSelected = 1 order by sales limit ?", dateStr,Constants.catesEn[i],Constants.catesSelectNums[i]);
			sum += n;
		}
		renderText(sum+"");
	}
	
	public void clearPublish() {
		String dateStr = getPara("date");
			int n = Db.update("update meitian set `publishDate` = null where `publishDate` =  ?", dateStr);
		renderText(n+"");
	}
	
	public Integer getCateNum(String cate) {
		for(int i=0; i<Constants.cates.length; i++) {
			if(Constants.cates[i].equals(cate)) {
				return Constants.catesSelectNums[i];
			}
		}
		return 0;
	}
	
	public void updateData() {
		System.out.println("hjaha");
	}
}
